$(document).ready(function() {
	var DestoutObj="";
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPWMSOPE : "XPWMSOPE" ,
        T_XPAPLYWO  : "XPAPLYWO"  ,
        T_XPINQCOD : "XPINQCOD",
        T_XPINQBOX : "XPINQBOX"
    };

//    var gDestList = [];

    var domObj = {
			$window : $(window),
			$ppboxInfoGrdDiv : $("#ppboxInfoGrdDiv"),
			$ppboxInfoGrd : $("#ppboxInfoGrd")
	};
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W              : $(window)           ,
        destShopSelect : $("#destShopSelect"),
        opeSelect      : $("#opeSelect")     ,
        woIdSelect     : $("#woIdSelect")  ,
        ppBoxIDInput   : $("#ppBoxIDInput")  ,
        shipUserInput : $("#shipUserInput")  ,
//        giveUserInput : $("#giveUserInput")  ,
        woPlnQtyTxt    : $("#woPlnQtyTxt")  ,
        woWhinQtyTxt     : $("#woWhinQtyTxt")   ,
        woDiffQtyTxt    : $("#woDiffQtyTxt")  ,
        mainGrd   :{
            grdId     : $("#ppboxInfoGrd")   ,
            grdPgText : "#ppboxInfoPg"       ,
            fatherDiv : $("#ppboxInfoGrdDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        query : $('#query_btn'),
        del : $('#delete_btn'),
        clr : $('#clear_btn'),
        add : $('#add_btn'),
        regist : $('#regist_btn'),
        change : $('#change_prd_admin_flg_btn'),
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.80);
//            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            controlsQuery.ppBoxIDInput.val("");
            controlsQuery.shipUserInput.val("");
            controlsQuery.woPlnQtyTxt.val("");
            controlsQuery.woWhinQtyTxt.val("");
            controlsQuery.woDiffQtyTxt.val("");
        },
        iniOpeSelect : function(){
            var inObj, outObj;

            inObj = {
                trx_id      : 'XPBISOPE',
                action_flg  : 'L'
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setOpeSelectDate(outObj.tbl_cnt, outObj.oary,
                    "ope_id", "ope_ver", "ope_dsc", controlsQuery.opeSelect, true);
            }
        },
        getCurOpe : function(){
            var ope_info,
                ope_info_ary,
                ope_id;

            ope_info = $.trim(controlsQuery.opeSelect.val());

            if(!ope_info){
                return false;
            }

            ope_info_ary = ope_info.split("@");
            ope_id = ope_info_ary[0];

            return ope_id;
        },
        setDestShopSel : function(){
        	var inObj,outObj;
        	var iary={
        		data_cate : 'DEST',
        		data_ext  : "'E'"   ,
        		user_id   : $("#userId").text()
        	};
        	inObj = {
			   trx_id     : 'XPLSTDAT' ,
	           action_flg : 'F'        ,
	           iary       : iary
        	};
        	DestoutObj = comTrxSubSendPostJson(inObj);
        	if(DestoutObj.rtn_code == VAL.NORMAL){
        		_setSelectDate(DestoutObj.tbl_cnt,DestoutObj.oary,"data_id","data_desc","#destShopSelect",true);
        	}
//            addValueByDataCateFnc("#destShopSelect","DEST","data_id", true);
        },
        iniWoIdSelect : function(){
            var inObj,
                outObj;
            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                iary : {
                    wo_stats : "'WAIT','CLOS'"
                }
            };

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", "wo_id", "#woIdSelect", true);
            }
        },
        addBoxInfoById : function( boxId ){
            var i,j,
                rowIds,
                wo_id,
                dest_shop,
                curRowData,
                curGrid = controlsQuery.mainGrd.grdId;

            if( !boxId ){
                console.error("Query boxId in null [%d]", boxId);
                return false;
            }

            rowIds = curGrid.jqGrid('getDataIDs');
            if(rowIds){
                for(i = 0, j = rowIds.length; i < j; i++) {
                    curRowData = curGrid.jqGrid('getRowData', rowIds[i]);
                    if( curRowData['box_id'] == boxId ){
                        showErrorDialog("", boxId+"已经存在！");
                        return false;
                    }
                }
            }

            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'I'           ,
                box_id      : boxId
            };
            wo_id = controlsQuery.woIdSelect.val();
            if(wo_id){
                inObj.wo_id = wo_id;
            }
            dest_shop = controlsQuery.destShopSelect.val();
            if(dest_shop){
                inObj.dest_shop = dest_shop;
            }

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                if( parseInt( outObj.box_cnt, 10) > 0 ){
                    if( "SHIP" != outObj.box_info.box_stat ){
                        showErrorDialog("","箱子状态为["+ outObj.box_info.box_stat +"],必须为[SHIP]!");
                        return false;
                    }
                    /**
                	 * 获取仓位描述
                	 * @author CMJ
                	 */
                    var desc = DestTrans.getTran("'E'",outObj.box_info.dest_shop);
                    outObj.box_info.dest_shop = desc==undefined ? outObj.box_info.dest_shop : desc;
                    
                    curGrid.jqGrid('addRowData', $.jgrid.randId(), outObj.box_info);
                    toolFunc.clearInput();
                }else{
                    showErrorDialog("","箱子["+ boxId +"]不存在！");
                    return false;
                }
            }

            return true;
        },
        getWoInfoFunc : function(){
            var wo_id,
                inObj,
                outObj;

            wo_id = controlsQuery.woIdSelect.val().trim();
            if(!wo_id){
                console.warn("wo_id [%s] is null!", wo_id);
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                tbl_cnt     : 1             ,
                iary : {
                    wo_id     : wo_id,
                    mtrl_cate : "SHMT"
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                controlsQuery.woPlnQtyTxt.val(outObj.oary.pln_prd_qty);
                controlsQuery.woWhinQtyTxt.val(outObj.oary.wip_wh_in_prd_qty);
                controlsQuery.woDiffQtyTxt.val( parseInt(outObj.oary.pln_prd_qty, 10) - parseInt(outObj.oary.wip_wh_in_prd_qty, 10) );
            }
            return true;
        },
        findBoxInGrid : function(){
            var box_id;

            box_id = $.trim(controlsQuery.ppBoxIDInput.val());
            if(!box_id){
                showErrorDialog("","请输入箱号!");
                return false;
            }

            _findRowInGrid('ppboxInfoGrdDiv', controlsQuery.mainGrd.grdId, 'box_id', box_id);
            return true;
        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Clear
        clear_func : function(){
            controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
        },
        //Delete
        del_func : function(){
            var i, j,
                curGrid = controlsQuery.mainGrd.grdId,
                ids = curGrid.jqGrid("getGridParam","selarrrow");
            for ( i = 0, j = ids.length; i < j; i++) {
                curGrid.jqGrid('delRowData', ids[0]);
            }
        },
        //ADD
        add_func : function(){
            var box_id;

            box_id = $.trim(controlsQuery.ppBoxIDInput.val());
            if(!box_id){
                showErrorDialog("","请输入箱号");
                return false;
            }

            toolFunc.addBoxInfoById(box_id);
            return true;
        },
        regist_func : function(){
            "use strict";
            var inObj,
                outObj,
                relate_usr,
                iary = [],
                ids,
                box_cnt,
                rowData,
                wo_id,
                curGrid = controlsQuery.mainGrd.grdId,
                i;

            relate_usr = $.trim(controlsQuery.shipUserInput.val());
            if(!relate_usr){
                showErrorDialog("","请输入收货人!");
                return false;
            }

            ids = curGrid.jqGrid("getGridParam","selarrrow");
            box_cnt = ids.length;
            if( box_cnt === 0 ){
                showErrorDialog("","请勾选需要出库的箱号!");
                return false;
            }

            for( i = 0; i < box_cnt; i++ ){
            	var errflg="YES";

                rowData = curGrid.jqGrid('getRowData', ids[i]);
                if(DestoutObj.tbl_cnt>1){
                    for(var d=0;d<DestoutObj.tbl_cnt;d++){
                  	  if(DestoutObj.oary[d].data_id!=rowData['dest_shop_dsc']){
                              continue;
                  	  }else{
                  		    errflg="NO";
                  	  }
                    }
                    if(errflg=="YES"){
                  	    showErrorDialog("","您没有操作箱子所属仓位的权限！");
                          return false;
                    }
                }else{
              	  if(DestoutObj.oary.data_id!=rowData['dest_shop_dsc']){
                        showErrorDialog("","您没有操作箱子所属仓位的权限！");
                        return false;
              	  }  
                }
               
                
                iary.push({
                    box_id : rowData['box_id'],
                    prd_qty : rowData['prd_qty'],
                    wo_id_fk : rowData['wo_id']
                });
            }

            inObj = {
                trx_id      : VAL.T_XPWMSOPE,
                action_flg  : 'W'           ,
                evt_user    : VAL.EVT_USER,//发料人员改为登陆人员
                relate_usr : relate_usr,
                box_cnt : ids.length,
                iary : iary
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                showSuccessDialog("出库成功！");
                toolFunc.getWoInfoFunc();
            }
            return true;
        },
        //Query by condition
        query_func : function(){
            "use strict";
            var inObj,
                outObj,
                wo_id,
                box_id,
                ope_id,
                oary,
                dest_shop,i;

            inObj = {
                trx_id       : VAL.T_XPINQBOX,
                action_flg   : 'I'           ,
                wip_bank_flg : 'Y'        ,
                box_stat     : "SHIP"
            };

            box_id = $.trim(controlsQuery.ppBoxIDInput.val());
            if(box_id){
                inObj.box_id = box_id;
            }
            ope_id = toolFunc.getCurOpe();
            if(ope_id){
                inObj.ope_id = ope_id;
            }

            wo_id = controlsQuery.woIdSelect.val();
            if(wo_id){
                inObj.wo_id = wo_id;
            }
            dest_shop = controlsQuery.destShopSelect.val();
            if(dest_shop){
                inObj.dest_shop = dest_shop;
            }

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                oary = _destListTool.addDestDesc(outObj.box_info,
                    'dest_shop', null, 'dest_shop');
                setGridInfo(oary, "#ppboxInfoGrd");
            }

            return true;
        },
        
        change_func : function (){
        	var inObj,
            outObj,
            iary = new Array();

        	var curGrid = controlsQuery.mainGrd.grdId,
            ids = curGrid.jqGrid("getGridParam","selarrrow");
        	for (var i=0;i<ids.length;i++){
        		var errflg="YES";
              
                var gridInfo = curGrid.jqGrid('getRowData', ids[i]);
                if(DestoutObj.tbl_cnt>1){
                    for(var d=0;d<DestoutObj.tbl_cnt;d++){
                  	  if(DestoutObj.oary[d].data_id!=gridInfo['dest_shop_dsc']){
                              continue;
                  	  }else{
                  		    errflg="NO";
                  	  }
                    }
                    if(errflg=="YES"){
                  	    showErrorDialog("","您没有操作箱子所属仓位的权限！");
                          return false;
                    }
                }else{
              	  if(DestoutObj.oary.data_id!=gridInfo['dest_shop_dsc']){
                        showErrorDialog("","您没有操作箱子所属仓位的权限！");
                        return false;
              	  }  
                }
               
        		
        		iary[i] = {};
        		iary[i].box_id = gridInfo.box_id;
        		iary[i].prd_admin_flg = gridInfo.prd_admin_flg;
        	}
       
        	inObj = {
	            trx_id      : VAL.T_XPINQBOX,
	            action_flg  : 'H'           ,
	            iary : iary
	        };
        	outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
            	btnFunc.query_func();
            	showSuccessDialog("变更成功！");
            }else{
            	showErrorDialog("", "变更失败！");
            }
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.query.click(function(){
            btnFunc.query_func();
        });
        btnQuery.del.click(function(){
            btnFunc.del_func();
        });
        btnQuery.clr.click(function(){
            btnFunc.clear_func();
        });
        btnQuery.add.click(function(){
            btnFunc.add_func();
        });
        btnQuery.regist.click(function(){
            btnFunc.regist_func();
        });
        btnQuery.change.click(function (){
        	btnFunc.change_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var infoCMNew = [
            {name: 'cus_id',      index: 'cus_id',     label: CUS_ID_TAG      , width: CUS_ID_CLM},
            {name: 'so_id',       index: 'so_id',      label: SO_NO_TAG       , width: WO_ID_CLM},
            {name: 'wo_id',       index: 'wo_id',      label: WO_ID_TAG       , width: WO_ID_CLM},
            {name: 'box_id',      index: 'box_id',     label: CRR_ID_TAG      , width: BOX_ID_CLM},
            {name: 'lot_id',      index: 'lot_id',     label: LOT_ID_TAG      , width: LOT_ID_CLM},
            {name: 'wh_in_timestamp',      index: 'wh_in_timestamp',     label: WH_IN_TIMESTAMP_TAG      , width: LOT_ID_CLM},

            {name: 'prd_qty',     index: 'prd_qty',    label: TOTAL_QTY_TAG   , width: QTY_CLM },
            {name: 'prd_admin_flg',index: 'prd_admin_flg',label:"出货标识", width : QTY_CLM},

            {name: 'mtrl_prod_id',   index: 'mtrl_prod_id',   label: FROM_MTRL_ID_TAG   , width: MTRL_PROD_ID_CLM},
            {name: 'mdl_id_fk',      index: 'mdl_id_fk',      label: TO_MTRL_ID_TAG     , width: MDL_ID_CLM},
            {name: 'fm_mdl_id_fk',   index: 'fm_mdl_id_fk',   label: FM_MDL_ID_TAG      , width: MDL_ID_CLM},
            {name: 'cut_mdl_id_fk',  index: 'cut_mdl_id_fk',  label: CUT_MDL_ID_TAG     , width: MDL_ID_CLM},
            {name: 'from_thickness', index: 'from_thickness', label: FROM_THICKNESS_TAG , width: QTY_CLM},
            {name: 'to_thickness',   index: 'to_thickness',   label: TO_THICKNESS_TAG   , width: QTY_CLM},

            {name: 'evt_usr',        index: 'evt_usr',        label: EVT_USR             , width: USER_CLM},
            {name: 'evt_timestamp',  index: 'evt_timestamp',  label: EVT_TIMESTAMP_TAG   , width: TIMESTAMP_CLM},
            {name: 'dest_shop' ,  index: 'dest_shop' , label: DEST_SHOP_TAG    , width: DEST_SHOP_CLM },
            {name: 'dest_shop_dsc',      index: 'dest_shop_dsc',      label: DEST_SHOP_TAG    , hidden : true},
            {name: 'box_weight',  index: 'box_weight', label: WEIGHT_TAG       , width: QTY_CLM },
            {name: 'box_stat'  ,  index: 'box_stat'  , label: STATUS_TAG       , width: PRD_STAT_CLM},
            {name: 'ok_cnt',  index: 'ok_cnt',  label: OK_CNT_TAG       , width: QTY_CLM },
            {name: 'ng_cnt',  index: 'ng_cnt',  label: NG_CNT_TAG       , width: QTY_CLM },
            {name: 'sc_cnt',  index: 'sc_cnt',  label: SC_CNT_TAG       , width: QTY_CLM },
            {name: 'gk_cnt',  index: 'gk_cnt',  label: GRADE_CONTROL_TAG, width: QTY_CLM },
            {name: 'lz_cnt',  index: 'lz_cnt',  label: GRADE_SCRP_TAG   , width: QTY_CLM }
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height: 360,
            width: 1050,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            multiselect : true,
            viewrecords:true,
            pager : controlsQuery.mainGrd.grdPgText,
            fixed: true,
            colModel: infoCMNew
        });
    };

    var shortCutKeyBind = function(){
        document.onkeydown = function(event) {
            if(event.keyCode == F1_KEY){
                btnQuery.query.click();
                return false;
            }else if(event.keyCode == F2_KEY){
                btnQuery.del.click();
                return false;
            }else if (event.keyCode == F3_KEY) {
                btnQuery.clr.click();
                return false;
            }else if (event.keyCode == F4_KEY) {
                btnQuery.add.click();
                return false;
            }else if (event.keyCode == F5_KEY) {
                btnQuery.regist.click();
                return false;
            }else if (event.keyCode == F6_KEY) {
            	btnQuery.change.click();
            	return false;
            }

            return true;
        };
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        controlsQuery.ppBoxIDInput.keydown(function(event){
            if(event.keyCode === 13){
                toolFunc.findBoxInGrid();
            }
        });

        controlsQuery.woIdSelect.change(function(){
            toolFunc.getWoInfoFunc();
        });

        shortCutKeyBind();
    };

    /**
     * Ini view and data
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();
        toolFunc.clearInput();

        //Ini dest shop
        toolFunc.setDestShopSel();
        //Ini ope
        toolFunc.iniOpeSelect();
        //Wo info
        toolFunc.iniWoIdSelect();
        toolFunc.getWoInfoFunc();
        // Dest Desc
        DestTrans.addTrans("'E'");

        //Ini dest id - dest desc
        _destListTool.ini();
    };

    initializationFunc();
    function resizeFnc(){                                                                      
    	var offsetBottom, divWidth; 
    	
		divWidth = domObj.$ppboxInfoGrdDiv.width();                                   
		offsetBottom = domObj.$window.height() - domObj.$ppboxInfoGrdDiv.offset().top;
		domObj.$ppboxInfoGrdDiv.height(offsetBottom * 0.90);                          
		domObj.$ppboxInfoGrd.setGridWidth(divWidth * 0.99);                   
		domObj.$ppboxInfoGrd.setGridHeight(offsetBottom * 0.99 - 51);               
    };                                                                                         
    resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc();                                                                             
	}); 
});